/*
 * @(#) TestController
 *
 * <br> Copyright:  Copyright (c) 2018

 * <br> @author wuxw
 * <br> 2018-08-24 17:22:20
 * ————————————————————————————————
 *    修改记录
 *    修改者：
 *    修改时间：
 *    修改原因：
 * ————————————————————————————————
 */

package com.boot.test.controller;

import com.boot.test.dto.request.LoginRequest;
import com.boot.test.entity.Tuser;
import com.boot.test.service.TuserService;
import com.boot.test.utils.PasswordUtil;
import com.boot.test.utils.ResponseTypeOutUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by wuxw on 2018/8/24.
 */

@Controller
@RequestMapping(value = "/login")
public class LoginController {

    @Autowired
    private TuserService tuserService;

    /**
     * 登录页
     * @param model
     * @return
     */
    @RequestMapping(value = "/index")
    public String  liginIndex(ModelAndView model) {
        return "login/loginIndex";
    }

    @RequestMapping(value = "/success")
    public String  successIndex(ModelAndView  model) {
        return "login/loginSuccess";
    }


    /**
     * 登录验证
     * @param oginRequest
     * @return
     */
    @RequestMapping
    public String logins(LoginRequest oginRequest) {
        Tuser tuser =  tuserService.findByAccount(oginRequest.getAccount());
        if(tuser!= null){
            String passwordReq = oginRequest.getPassword();
            String password = PasswordUtil.entryptPassword(passwordReq);
            if(password.endsWith(tuser.getPassword())){
                return  "redirect:login/success";
            }
        }
        return "404";
    }

    /**
     * 注册用户
     */
    @RequestMapping("/save")
    public void saveUser(HttpServletRequest request, HttpServletResponse response) {
        String account = request.getParameter("account");
        String passwordReq = request.getParameter("password");
        Tuser tuser =  tuserService.findByAccount(account);
        if(tuser == null){
            Tuser user = new Tuser();
            user.setName("test");
            user.setAccount(account);
            //设置密码，对密码加密
            String password = PasswordUtil.entryptPassword(passwordReq);
            user.setPassword(password);
            user.setPhone("13600000000");
            user.setCreateBy("by-system");
            user.setCreateTime(new Date());
            tuserService.saveEntity(user);
            ResponseTypeOutUtils.renderJsonSuccess(response, "注册成功");
            return;
        }
        ResponseTypeOutUtils.renderJsonSuccess(response, "已存在账号");
    }

}
